package com.yuexun.dhdoctor.module.my.ui;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.ExitApplication;
import com.yuexun.dhdoctor.baselistener.ICallBackListener;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.login.ui.Act_Login;
import com.yuexun.dhdoctor.module.main.bean.UpdateBean;
import com.yuexun.dhdoctor.module.main.model.impl.UpdateModel;
import com.yuexun.dhdoctor.module.main.presenter.IUpdatePresenter;
import com.yuexun.dhdoctor.module.main.presenter.impl.UpdatePresenter;
import com.yuexun.dhdoctor.module.main.ui.view.IUpdateView;
import com.yuexun.dhdoctor.module.my.bean.MessageCountBean;
import com.yuexun.dhdoctor.module.my.model.impl.MyModel;
import com.yuexun.dhdoctor.module.my.presenter.impl.MyPresenter;
import com.yuexun.dhdoctor.module.my.ui.view.IMyView;
import com.yuexun.dhdoctor.util.UpdateManager;
import com.yuexun.dhdoctor.widget.LoadingDialog;

import org.kymjs.kjframe.ui.SupportFragment;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by chenss on 2018/5/4 0004.
 */

public class Frag_My extends SupportFragment implements IUpdateView, IMyView {

    @Bind(R.id.ic_message_count)
    TextView icMessageCount;
    @Bind(R.id.my_pic)
    ImageView myPic;
    @Bind(R.id.my_name)
    TextView myName;
    @Bind(R.id.my_dept)
    TextView myDept;
    @Bind(R.id.my_id_tv)
    TextView myIdTv;
    @Bind(R.id.my_id)
    TextView myId;
    @Bind(R.id.ic_code)
    ImageView icCode;
    @Bind(R.id.ic_sign)
    ImageView icSign;
    @Bind(R.id.ic_clean)
    ImageView icClean;
    @Bind(R.id.ic_lock)
    ImageView icLock;
    @Bind(R.id.my_lock_check)
    CheckBox myLockCheck;
    @Bind(R.id.ic_login_password)
    ImageView icLoginPassword;
    @Bind(R.id.ic_share)
    ImageView icShare;
    @Bind(R.id.ic_feedback)
    ImageView icFeedback;
    @Bind(R.id.ic_update)
    ImageView icUpdate;
    @Bind(R.id.my_version)
    TextView myVersion;
    @Bind(R.id.update_ic_arrow)
    ImageView updateIcArrow;

    Boolean ispassword;
    LoadingDialog loadingDialog;
    Handler handler_blood;
    Timer time;
    TimerTask timetask;
    int countTime = 3;
    int allcount = 0;
    IUpdatePresenter presenter;
    MyPresenter myPresenter;

    ICallBackListener listener;

    public void setBackListener(ICallBackListener listener) {
        this.listener = listener;
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View view = inflater.inflate(R.layout.frag_my, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initData() {
        super.initData();
        myPresenter = new MyPresenter(new MyModel(), this);
        myName.setText(PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.USER_NAME));
        myDept.setText(PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.DEPARTMENTNAME));
        myId.setText(PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.JOB_ID));

        try {
            myVersion.setText(getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        presenter = new UpdatePresenter(new UpdateModel(), this);

        myLockCheck.setChecked(false);
        myLockCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (myLockCheck.isChecked()) {
                    Intent intent_lock = new Intent(getActivity(), Act_EasyPassword.class);
                    startActivity(intent_lock);
                } else {
                    Intent intent_lock = new Intent(getActivity(), Act_CanclePassword.class);
                    startActivity(intent_lock);
                }
            }
        });

        loadingDialog = new LoadingDialog(getActivity());
    }

    @Override
    public void onResume() {
        super.onResume();
        ispassword = PreferenceHelper.readBoolean(getActivity(), AppConfig.USER_INFO, AppConfig.ISPASSWORD);
        if (ispassword) {
            myLockCheck.setChecked(true);
        } else {
            myLockCheck.setChecked(false);
        }

        allcount = 0;
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("targetId", "2");
        params.put("state", "0");
        myPresenter.getMessageCount(params);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.ic_message_icon, R.id.my_code_ll, R.id.my_sign_ll, R.id.my_message_ll, R.id.my_lock_ll, R.id.my_login_password_ll, R.id.my_share_ll, R.id.my_feedback_ll, R.id.my_update_ll, R.id.my_out})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ic_message_icon:
                break;
            case R.id.my_code_ll:
                Intent intent1 = new Intent(getActivity(), Act_Qrcode.class);
                startActivity(intent1);
                break;
            case R.id.my_sign_ll:
                Intent intent2 = new Intent(getActivity(), Act_Sign.class);
                startActivity(intent2);
                break;
            case R.id.my_message_ll:
                loadingDialog.show();
                handler_blood = new Handler() {
                    public void handleMessage(Message msg) {
                        if (msg.what > 0) {
                            Log.v("time", msg.what + "");
                        } else {
                            countTime = 3;
                            if (time != null) {
                                time.cancel();
                                time = null;
                            }

                            if (timetask != null) {
                                timetask.cancel();
                                timetask = null;
                            }
                            loadingDialog.dismiss();
                            Toast.makeText(getActivity(), "已清除缓存", Toast.LENGTH_SHORT).show();
                        }
                        super.handleMessage(msg);
                    }

                };

                time = new Timer(true);
                timetask = new TimerTask() {
                    public void run() {
                        if (countTime > 0) {
                            countTime--;
                        }
                        Message msg = new Message();
                        msg.what = countTime;
                        handler_blood.sendMessage(msg);
                    }

                };
                time.schedule(timetask, 0, 1000);
                break;
            case R.id.my_lock_ll:
                break;
            case R.id.my_login_password_ll:
                startActivity(new Intent(getActivity(), Act_Change_Psw.class));
                break;
            case R.id.my_share_ll:
                Intent intent_share = new Intent(getActivity(), Act_Share.class);
                startActivity(intent_share);
                break;
            case R.id.my_feedback_ll:
                Intent intent_feedback = new Intent(getActivity(), Act_Feedback.class);
                startActivity(intent_feedback);
                break;
            case R.id.my_update_ll:
                presenter.update();
                break;
            case R.id.my_out:
                PreferenceHelper.write(getActivity(), AppConfig.USER_INFO, AppConfig.ISLOGIN, false);
                Intent intent = new Intent(getActivity(), Act_Login.class);
                startActivity(intent);
                ExitApplication.getInstance().exit();

//                AppContext appContext = (AppContext) getActivity().getApplicationContext();
//                appContext.custom = "";
//                appContext.mPushAgent.deleteAlias(PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.ACCOUNT_ID),
//                        "ACCOUNT_ID", new UTrack.ICallBack() {
//                            @Override
//                            public void onMessage(boolean isSuccess, String message) {
//
//                            }
//                        });
                break;
        }
    }

    @Override
    public void showUpdateInfo(UpdateBean updateBean) {
        try {
            int versionCode = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionCode;
            if (updateBean.getVersionCode() > versionCode) {
                UpdateManager updateManager = new UpdateManager(getActivity(), updateBean, versionCode);
                updateManager.showNoticeDialog();
            } else {
                Toast.makeText(getActivity(), "已经是最新版本", Toast.LENGTH_LONG).show();
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showUpdateError() {

    }

    @Override
    public void showMessageCount(MessageCountBean messageCountBean) {
        if (messageCountBean.getStatus().equals("200")) {
            allcount = allcount + Integer.valueOf(messageCountBean.getDatas().get(0));
            if (listener != null) {
                Bundle bundle = new Bundle();
                bundle.putInt("count", allcount);
                listener.callback(bundle);
            }
            if (Integer.valueOf(messageCountBean.getDatas().get(0)) > 0) {
                icMessageCount.setVisibility(View.VISIBLE);
                icMessageCount.setText(messageCountBean.getDatas().get(0));
            } else {
                icMessageCount.setVisibility(View.GONE);
                icMessageCount.setText("");
            }
        }
    }
}
